package com.zh.stargraph2.comfyui.client.config;

import com.zh.stargraph2.comfyui.client.api.ComfyuiApi;
import com.zh.stargraph2.comfyui.client.handler.ComfyuiMessageHandler;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Configuration
public class ComfyuiConfig {

    @Bean
    // 把消息处理ComfyuiMessageHandler类注册成Bean
    public ComfyuiMessageHandler comfyuiMessageHandler(){
        return new ComfyuiMessageHandler();
    }

    // 注册连接管理器Bean
    @Bean
    public WebSocketConnectionManager webSocketConnectionManager(ComfyuiMessageHandler comfyuiMessageHandler){
        StandardWebSocketClient client = new StandardWebSocketClient();
        String url = "ws://192.168.100.129:8188/ws?clientId=star-graph";
        WebSocketConnectionManager manager = new WebSocketConnectionManager(client,comfyuiMessageHandler,url);
        manager.start();
        return manager;
    }

    @Bean
    public ComfyuiApi comfyuiApi() throws IOException {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(30, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.100.129:8188")
                .client(okHttpClient)
                .addConverterFactory(JacksonConverterFactory.create())
                .build();

        ComfyuiApi comfyuiApi = retrofit.create(ComfyuiApi.class);
        return comfyuiApi;
    }

}
